<template>
  <el-dialog
    class="pick-dialog"
    :title="title"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="1100px"
  >
    <div class="form-box" v-loading="loading"> 
      <div class="orderTable" >
        <el-table :data="orderList" border style="width: 100%">
          <el-table-column prop="saleChannel" label="买家"></el-table-column>
          <el-table-column prop="supplyChannel" label="卖家"></el-table-column>
          <el-table-column
            prop="no"
            label="售后编号"
            min-width="150"
          ></el-table-column>
          <el-table-column prop="goodsId" label="商品编号"> </el-table-column>
          <el-table-column prop="accountNumber" label="游戏账号"> </el-table-column>

          <el-table-column
            prop="afterAmount"
            label="退款金额"
          ></el-table-column>
          <el-table-column
            prop="platformPayAmount"
            label="平台应付"
          ></el-table-column>
          <el-table-column
            prop="sellerPayAmount"
            label="卖家应付"
          ></el-table-column>
          <el-table-column
            prop=""
            label="买家结算状态"
            v-if="from == 'buyer'"
          >
            <template slot-scope="scope">
              <el-tag
                :type="
                  commonMaps.sellerPayState[scope.row.saleSettlementState].type
                "
                >{{
                  commonMaps.sellerPayState[scope.row.saleSettlementState]
                    .label || commonMaps.sellerPayState["1"].label
                }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop=""
            label="卖家结算状态"
            v-if="from == 'seller'"
          >
            <template slot-scope="scope">
              <el-tag
                :type="
                  commonMaps.sellerPayState[scope.row.supplySettlementState]
                    .type
                "
                >{{
                  commonMaps.sellerPayState[scope.row.supplySettlementState]
                    .label || commonMaps.sellerPayState["1"].label
                }}</el-tag
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="total-amount flex">
          <h3>{{ from == "buyer" ? "应付给买家：" : "应收卖家：" }}</h3>
          <div class="price">
            {{ from == "buyer" ? info.afterAmount : info.sellerPayAmount }}元
          </div>
        </div>
      </div>
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="auto"
        :rules="rules"
        class="demo-ruleForm"
      >
      <el-form-item :label=" from == 'buyer' ? '买家余额：' : '卖家余额：'" >
          <span style="font-size:18px;font-weight:600">{{otherUserInfo.availableMoney}}</span>
        </el-form-item>
        <el-form-item label="结算方式:" prop="settlementType">
          <el-radio-group v-model="ruleForm.settlementType">
            <el-radio
              v-for="(item, key) in commonMaps.settlementTypeMap"
              :key="key"
              :label="key"
              >{{ item }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        
        <el-form-item
          label="上传图片:"
          prop="afterImg"
          v-if="ruleForm.settlementType == 2"
        >
          <el-upload
            :action="uploadImgUrl"
            list-type="picture-card"
            :file-list="imgShowList0"
            :multiple="true"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess0"
            :on-remove="handleRemove0"
            :limit="9"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="补充描述:" prop="remark">
          <el-input
            style="width: 600px"
            v-model="ruleForm.remark"
            type="textarea"
            rows="5"
            placeholder="请输入结算补充描述..."
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="center">
        <el-button @click="close('ruleForm')">关闭</el-button>
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          :loading="loading"
          >{{ from == "seller" ? "确认结算" : "确认结算" }}</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<script>
import orderAfterApi from "@/api/pickUp/afterSale.js";
import billListApi from "@/api/financeCenter/billList.js";
import { getUser } from "@/api/system/user"
export default {
  name: "",
  data() {
    return {
      title: "买家结算",
      dialogVisible: false,
      loading: false,
      // 上传相关
      uploadImgUrl: "",
      imgShowList0: [],
      newImages0: [],
      imgFileList0: [],
      // end
      ruleForm: {
        typeReq: "", //1买家结算 2卖家结算
        orderIds: [],
        settlementType: "1",
        userId: "",
        userName: "",
        img: "",
        remark: "",
      },
      rules: {},
      from: "", //来源
      buyerOrSeller: "",
      buyers: [],
      sellers: [],
      orderList: [],
      selectOrders: [],
      totalAmount: 0, //选中项的合计总额

      info: {},
      otherUserInfo:{},//要结算的买家或卖家信息  包含钱包余额
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
  },
  methods: {
    open(id, from) {
      this.loading = false;
      this.from = from;
      this.imgShowList0 = [];
      this.newImages0 = [];
      this.imgFileList0 = [];
      this.ruleForm = {
        typeReq: "", //1买家结算 2卖家结算
        orderIds: [],
        settlementType: "1",
        userId: "",
        userName: "",
        img: "",
        remark: "",
      };
      this.ruleForm.orderIds = [id];
      this.getAfterOrderInfo(id);
      this.buyerOrSeller = "";
      this.dialogVisible = true;
    },
    // 获取用户 信息 
    getOtherUserInfo(){
      getUser(this.ruleForm.userId).then(res=>{
        this.otherUserInfo =res.data
      })
    },
    // 获取售后订单详情
    getAfterOrderInfo(id) {
      this.loading = true;
      orderAfterApi.saleOrderInfoById(id, { dataType: "all" }).then((res) => {
        this.info = res.data;
        this.orderList = [res.data];
        this.loading = false;
        if ((this.from == "buyer")) {
          this.title = "买家结算";
          this.ruleForm.typeReq = 1;
          this.ruleForm.userId = this.info.saleChanelId;
          this.ruleForm.userName = this.info.saleChannel;
        } else {
          this.title == "卖家结算";
          this.ruleForm.typeReq = 2;
          this.ruleForm.userId = this.info.supplyChanelId;
          this.ruleForm.userName = this.info.supplyChannel;
        }
        this.getOtherUserInfo()
      });
    },

    submitForm(formName) {
      if (!this.ruleForm.orderIds || this.ruleForm.orderIds.length == 0) {
        return this.$message.error("请选择要结算的订单");
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // financialStatementSaleOrder
          // 组装图片附件
          // 拼接新上传的图片
          let ziliao = [];
          if (this["newImages0"] && this["newImages0"].length) {
            let newArr = [];
            this["newImages0"].forEach((img) => {
              newArr.push({
                name: img.name,
                url: img.response.data.filePath,
              });
            });
            ziliao = this["imgFileList0"].concat(newArr);
          } else {
            ziliao = this["imgFileList0"];
          }
          // ziliao
          // console.log("%c Line:212 🍖 ziliao", "color:#f5ce50", ziliao);
          this.ruleForm.img = JSON.stringify(ziliao);
          this.loading = true;
          billListApi.saleAfterSettled(this.ruleForm).then((res) => {
            this.dialogVisible = false;
            this.loading = false;
            if (res.code == 200) {
              this.$message.success(res.msg);
              this.$parent.getList();
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 上传图片相关
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传9张图片");
    },
    // 图片上传成功
    handleUploadSuccess0(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages0 = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 图片删除
    handleRemove0(response) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList0.splice(key, 1); //回显的图片
        }
      });
      this.newImages0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages0.splice(key, 1); //新上传的图片
        }
      });
    },
    close(formName) {
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">

.topBtn {
  margin-bottom: 20px;
}
.orderTable {
  margin-top: 20px;
}
.total-amount {
  line-height: 50px;
}
.price {
  font-size: 24px;
  color: crimson;
}
// .names {
//   margin: 20px 0;
// }
.demo-ruleForm {
  margin-top: 20px;
  padding-right: 20px;
}

.center {
  text-align: center;
}



.pick-dialog >>> .el-input--medium input {
  text-align: left;
}
</style>
